import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Hashtable;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

public class Util {
	public static String sendHttpGet(String url) throws IOException {
		HttpConnection hcon = null;
		DataInputStream dis = null;
		StringBuffer strbuf = new StringBuffer();

		hcon = (HttpConnection) Connector.open(url);
		dis = new DataInputStream(hcon.openInputStream());

		int read = 0;
		byte[] buf = new byte[4096];
		while ((read = dis.read(buf)) != -1) {
			strbuf = strbuf.append(new String(buf, 0, read));
		}

		dis.close();
		hcon.close();

		return new String(strbuf);
	}

	public static String sendHttpPost(final String url, Hashtable data) throws IOException {
		final StringBuffer requestBody = new StringBuffer();
		// requestBody.append("\r\n\r\n");

		Enumeration keys = data.keys();
		while (keys.hasMoreElements()) {
			String key = (String) keys.nextElement();
			requestBody.append(key);
			requestBody.append("=");
			requestBody.append(data.get(key));
			requestBody.append("&");
		}
		requestBody.deleteCharAt(requestBody.length()-1);
		
		new Thread() {
			public void run() {
				try {
					HttpConnection connection = (HttpConnection) Connector.open(url, Connector.READ_WRITE);
					connection.setRequestMethod(HttpConnection.POST);
					connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
					
					DataOutputStream out = new DataOutputStream(connection
							.openDataOutputStream());


					out.write(new String(requestBody).getBytes());
					out.flush();
					out.close();
					
					System.out.println(new String(requestBody));

					DataInputStream in = new DataInputStream(connection.openInputStream());

					int read = 0;
					byte[] buf = new byte[4096];
					StringBuffer strbuf = new StringBuffer();
					while ((read = in.read(buf)) != -1) {
						strbuf = strbuf.append(new String(buf, 0, read));
					}

					in.close();
					connection.close();
				}
				catch(Exception e) {
					e.printStackTrace();
				}
			}
		}.start();
		
		return null;
	}
}
